package com.plan.dao.hibernate;

import java.io.File;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;

import org.apache.log4j.Logger;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.hibernate.classic.Session;
import org.springframework.context.annotation.DependsOn;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;

import com.plan.login.entity.LoginEntity;

/**
 *hibernate 工具类
 * @author wangzih
 */
@Component("plan_hibernate")
@DependsOn("plan_log4j")
@Lazy(false)
public class HebernateInit {
	Logger logger=Logger.getLogger(HebernateInit.class);
	private String FILEPATH="src/com/config/hibernate.cfg.xml";
	private static SessionFactory sessionFactory;
	public void init(){
		logger.info("初始化数据库");
		File file=new File(FILEPATH);
		sessionFactory=new Configuration().configure(file).buildSessionFactory();
		Session openSession = sessionFactory.openSession();
		Connection connection =openSession.connection();
		try{
			Statement createStatement = connection.createStatement();
			try{
				createStatement.execute("select 123 from dual");
				logger.info("数据库初始化成功");
			}finally{
				createStatement.close();
			}
		}catch(Exception e){
			logger.info("数据库初始化失败");
		}finally{
			if(connection!=null){
				try {
					connection.close();
				} catch (SQLException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
					logger.info("数据库链接关闭失败");
				}
			}
		}
	}
	public static Session getSession(){
		return sessionFactory.openSession();
	}
	public static void main(String[] args) {
		File file=new File("src/com/config/hibernate.cfg.xml");
		System.out.println(file.exists());
		
		Session session = sessionFactory.openSession();
		try{
			Transaction tx = session.beginTransaction();
			LoginEntity le=new LoginEntity();
			le.setId("1233333");
			le.setPwd("4333356");
			session.save(le);
			tx.commit();
		}catch(Exception e){
			System.out.println(e.getCause());
		}
		finally{
			session.close();
		}
	}
}
